package com.tencent.elife.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

/**
 * @author zijianlu
 * @version 创建时间：2012-1-10 下午3:51:37
 * @Description 常用函数
 */
public class AppUtils {
    private static final String TAG = "elife.AppUtils";

    /** 获取当前应用的版本号 */
    public static String getVersionName(Context context) {
        String versionName = "";
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                0);
            versionName = packInfo.versionName;
        } catch (NameNotFoundException e) {
        }
        L.D(TAG, "getVersionName:" + versionName);
        return versionName;
    }

    /**
     * 按wtlogin的规则，将版本号转换为数字： 1.1 表示为 0x101, 1.0.1表示为0x10001
     * 1.0.1.1表示为0x1000101
     */
    public static int getVersionNameHex(Context context) {
        try {
            String verName = getVersionName(context);
            String str = verName.replace(".", "0");
            int version = Integer.valueOf(str, 16);
            L.D(TAG, "getVersionNameHex:" + str);
            return version;

        } catch (Exception e) {
            L.D(TAG, "getVersionNameHex:" + e.toString());
            e.printStackTrace();
        }

        return 0;
    }

    public static void disableConnectionReuseIfNecessary() {
        if (Integer.parseInt(Build.VERSION.SDK) < 8) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    /** 获取字符串的MD5值 */
    public static String toMD5(String str) {
        try {
            return toMD5(str.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    private static String toMD5(byte[] bytes) {
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(bytes);
            return toHexString(algorithm.digest(), "");
        } catch (NoSuchAlgorithmException e) {
        }
        return "";
    }

    private static String toHexString(byte[] bytes, String separator) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex).append(separator);
        }
        return hexString.toString();
    }

    /** 将bitmap转为圆角的图片 */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);

            final int color = 0xff313131;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            final float roundPx = pixels;

            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);

            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }

            return output;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }

        return null;
    }

    /** sd卡是否可用 */
    public static boolean isSDCardAviliable() {
        return Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED);
    }

    /** 获取sd卡剩余存储空间 , 单位M */
    public static long getSDCardFreeSpace() {
        if (isSDCardAviliable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long availableBlocks = stat.getAvailableBlocks();
            long freeSize = availableBlocks * blockSize / 1024 / 1024;
            L.D(TAG, "sdcard freespace:" + freeSize + "M");
            return freeSize;
        } else {
            L.E(TAG, "sdcard freespace:" + 0 + "M");
            return 0;
        }
    }

    /** 获取手机内部剩余存储空间, 单位M */
    public static long getInternalFreeSpace() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        long freeSize = availableBlocks * blockSize / 1024 / 1024;
        L.D(TAG, "Internal freespace:" + freeSize + "M");
        return freeSize;
    }

    /** 打电话 */
    public static void makeCall(String telphoneNum, Context ctx) {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
            + telphoneNum));
        ctx.startActivity(intent);
    }

    /** 删除单个的文件 */
    public static boolean delFile(String path) {
        if (!TextUtils.isEmpty(path)) {
            File file = new File(path);
            if (file.exists() && file.isFile()) {
                return file.delete();
            }
        }
        return false;
    }

}
